import { createRouter, createWebHashHistory } from 'vue-router'
import Layout from '@/Layout'
import store from '@/store'
const routes = [
  {
    path: '/', // 默认访问的根路径都是 /
    component: Layout,
    children: [
      {
        path: '', // 默认匹配的二级路由，一级路由匹配后，此路由直接生效在挂载点
        component: () => import('@/views/home')
      }
    ]
  },
  {
    path: '/category/:categoryid/:categoryname',
    component: Layout,
    children: [
      {
        path: '',
        component: () => import('@/views/category')
      }
    ]
  },
  {
    path: '/search',
    component: Layout,
    children: [
      {
        path: '',
        component: () => import('@/views/search')
      }
    ]
  },
  {
    path: '/goods',
    component: Layout,
    children: [
      {
        path: '',
        component: () => import('@/views/goods')
      }
    ]
  },
  {
    path: '/login',
    component: () => import('@/views/login')
  },
  {
    path: '/cart',
    component: Layout,
    children: [
      {
        path: '',
        component: () => import('@/views/cart')
      }
    ]
  },
  {
    path: '/user/order',
    component: Layout,
    children: [
      {
        path: '',
        component: () => import('@/views/order')
      }
    ]
  },
  {
    path: '/user/pay',
    component: Layout,
    children: [
      {
        path: '',
        component: () => import('@/views/pay')
      },
      {
        path: 'result',
        component: () => import('@/views/pay/result.vue')
      }
    ]
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes,
  // 路由跳转页面滚动到顶部
  scrollBehavior (to, from, savedPosition) {
    return { top: 0 }
  }
})

// 添加路由前置守卫
router.beforeEach((to, from, next) => {
  if (to.path.startsWith('/user') && !store.state.user.profile.token) {
    next('/login')
  } else {
    next()
  }
})
export default router
